import { clearToken, getToken, setToken } from "@/utils/auth";
import { defineStore } from "pinia";
import { computed, reactive, ref } from "vue";
import { login as loginApi, logout as logoutApi } from "@/apis/userApi";
import { resetRouter } from "@/router";

const storeSetup = () => {
  const userInfo = reactive({
    id: "",
    username: "",
    name: "",
    avatar: "",
  });

  const userName = computed(() => userInfo.name);
  const avatar = computed(() => userInfo.avatar);

  const token = ref(getToken() || "");
  const roles = ref([]); //用户角色
  const premissions = ref([]); // 角色权限

  //重置token
  const resetToken = () => {
    token.value = "";
    clearToken();
  };

  //登录
  const login = async (params) => {
    const res = await loginApi(params);
    console.log("login", res);
    setToken(res?.data?.token);
    token.value = res?.data?.token;
  };

  //退出
  const logout = async (params) => {
    const res = await logoutApi(params);
    console.log("logout", res);
    token.value = "";
    roles.value = [];
    premissions.value = [];
    clearToken();
    resetRouter();
  };

  return {
    userInfo,
    userName,
    avatar,
    token,
    premissions,
    login,
    logout,
  };
};

export const useUserStore = defineStore("user", storeSetup, {
  persist: { paths: ["token"], storage: localStorage },
});
